package q145_postorderTraversal;

import CommonClass.Common.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Solution_2 {

    public List<Integer> postorderTraversal(TreeNode root) {

        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }

        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode node = root;
        // 对于后序遍历需要一个节点记录上一个节点
        TreeNode prev = null;
        while (!stack.isEmpty() || node != null){

            while (node != null) {
                stack.push(node);
                node = node.left;
            }

            node = stack.pop();
            if (node.right == null || node.right == prev){
                res.add(node.val);
                prev = node;
                node = null;
            }else {
                stack.push(node);
                node = node.right;
            }

        }

        return res;

    }
}
